package com.example.nutritionmate.repository;

import com.example.nutritionmate.entity.MealNutrition;
import com.example.nutritionmate.entity.MealNutritionId;
import com.example.nutritionmate.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface MealNutritionRepository extends JpaRepository<MealNutrition, MealNutritionId> {
    @Query("SELECT SUM(mn.amount) FROM MealNutrition mn " +
            "WHERE mn.mealRecord.user = :user " +
            "AND mn.nutritionFact.nutritionNameEn = 'Calories' " +
            "AND mn.mealRecord.meal.date >= :startOfDay " +
            "AND mn.mealRecord.meal.date < :endOfDay")
    Double getTotalCaloriesByUserByDateBetween(@Param("user") User user,
                                               @Param("startOfDay") LocalDateTime startOfDay,
                                               @Param("endOfDay") LocalDateTime endOfDay);

//    @Query("SELECT SUM(mn.amount) FROM MealNutrition mn " +
//            "WHERE mn.mealRecord.user = :user " +
//            "AND mn.nutritionFact.nutritionNameEn = 'Calories' " +
//            "AND mn.mealRecord.meal.date = :date")
//    Double getTotalCaloriesByUserByDate(@Param("user") User user, @Param("date") LocalDate date);
    @Query("SELECT SUM(mn.amount) FROM MealNutrition mn " +
            "WHERE mn.mealRecord.user = :user " +
            "AND mn.nutritionFact.nutritionNameEn = 'Calories' " +
            "AND mn.mealRecord.meal.date = :date")
    Double getTotalCaloriesByUserByDate(@Param("user") User user, @Param("date") LocalDate date);

    @Query("SELECT mn.nutritionFact.nutritionId AS nutritionId, mn.nutritionFact.nutritionName AS nutritionName, SUM(mn.amount) AS totalAmount, mn.nutritionFact.unit AS unit " +
            "FROM MealNutrition mn " +
            "WHERE mn.mealRecord.user = :user AND mn.mealRecord.meal.date = :date " +
            "GROUP BY mn.nutritionFact.nutritionId, mn.nutritionFact.nutritionName")
    List<NutritionSummary> findNutritionSummaryByUserAndDate(@Param("user") User user, @Param("date") LocalDate date);
    /**
     * 投影接口，用于接收营养成分汇总查询结果
     */
    interface NutritionSummary {
        String getNutritionName();
        Double getTotalAmount();
        Integer getNutritionId();
        String getUnit();
    }
}
